const t = getApp()
let objectArraySort = function (keyName) {
  return function (objectN, objectM) {
   let valueN = objectN[keyName]
   let valueM = objectM[keyName]
   if (valueN < valueM) return 1
   else if (valueN > valueM) return -1
   else return 0
  }
}
Page({
  data: {
    iconsUrl:t.globalData.iconsUrl,
    change:0,
    choosed_money:null,
    InvestList:null,
		balance:0, //专用余额
		general_balance:0,//本金
		storebalance:0, //本店
		is_general:0,//是否通用门店
    title:'',
    tabIndex:0,
    log:[],
    store_id:null,
    vipList:null,
    myCard:null,
    change:0,
    page:1,
    total:0,
    canpre:false,
    cannext:false,
    wash_log:[],
    navHeight:t.globalData.navHeight,
    title:'充值',
    card_id:"",
    user_id:"",
    use_store:"",
    first_recharge:0,
		first_coupon:'',
		dis:'',//门店距离
		//支付成功弹窗 
    showStatus:false,
    duration: 300, //动画时长，单位毫秒
    position: 'bottom',
    round: true,  //是否显示圆角
    overlay: true, //是否显示遮罩层
    customStyle: '',//自定义弹出层样式
		overlayStyle: '', //自定义遮罩层样式
		// 订单编号
		orderNum:'',
		payTime:"",//支付时间
		interval:"",//定时器
		seconds:3, //倒计时3秒
		// 回跳地址
		lastUrl:'',
  },
  // 生命周期
  // 页面加载的时候执行一次
  onLoad(e){
    let card_id = '',dis='';
		if(e.card_id != undefined){card_id=e.card_id}   
		if(e.dis != undefined){dis=e.dis}                      
    this.setData({
      store_id:e.store_id,
			card_id,
			dis
    })
  },
  onShow(e){
    //判断手机是否登录了
    if (t.globalData.show_tel_login) {
      t.showTelLogin()
      return;
		}
		// 计算充值后回跳地址
		this.getLastUrl()
    this.getlist()
    this.getInvestList()
    // this.getList_new()
  },
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    this.getlist()
    this.getInvestList()
    // this.getList_new()
  },
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
    setTimeout(function () {
      // 不加这个方法真机下拉会一直处于刷新状态，无法复位
      wx.stopPullDownRefresh()
    }, 1000)
  },
  getlist(e){
    var that = this
    var loc = t.globalData.loc
    t.request('/store/index_list',{lat:loc?loc.latitude:0,lng:loc?loc.longitude:0,page:1},function(e){
      if (e.code!==200) return wx.showToast({ title: e.msg,icon:'none' })
      if (e.result.total>0) {
        let list = e.result.list
        list.forEach(ele => {
          ele.distance = ele.distance.toFixed(1)
        });
        that.setData({
          list,loc
        })
      }
    })
  },
  getInvestList(e){
    const that = this
    t.request('/RechargeConfig/getList',{store_id:that.data.store_id,card_id:that.data.card_id},function(e){
      if (e.code!==200) return wx.showToast({ title: e.msg,icon:'none' })
      let list = e.result.config.list
      // list.sort(objectArraySort('sort'))
			// console.log(list);
      that.setData({
        InvestList:list,
				balance:e.result.balance,//专用余额
				general_balance:e.result.general_balance,//本金
				is_general:e.result.is_general,//是否通用门店
				storebalance:e.result.store_balance,//本店
        title:e.result.title,
        user_id:e.result.user_id,
        use_store:e.result.use_store,
        first_recharge:e.result.first_recharge,
        first_coupon:e.result.first_coupon,
      })
    })
  },
  getList_new(e){
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    let change=that.data.change;
    if(change==1){
      t.request('/users/Washing_log',{page:this.data.page},function(res){
        if (res.code==200) {
         console.log(res);
         let cannext=false;
         if(res.result.total>that.data.page){
          cannext=true;
        }
         that.setData({
          wash_log:res.result.data,
          total:res.result.total,
          cannext:cannext
        })
        wx.hideLoading({
          success: (res) => {},
        })
        }
      })
    }else{
      t.request('/users/Recharge_log',{page:this.data.page},function(res){
        if (res.code==200) {
         console.log(res);
         let cannext=false;
         if(res.result.total>that.data.page){
          cannext=true;
        }
         that.setData({
          log:res.result.data,
          total:res.result.total,
          cannext:cannext
        })
        wx.hideLoading({
          success: (res) => {},
        })
        }
      })
    }
    
  },
  getVip(e){
    const that = this
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    t.request('/RechargeConfig/getVip',{store_id:that.data.store_id},function(e){
      console.log(e);
      wx.hideLoading({
        success: (res) => {},
      })
      if (e.code!==200) return wx.showToast({ title: e.msg,icon:'none' })
      let list = e.result.cardlist.list
      list.sort(objectArraySort('sort'))
      that.setData({
        vipList:list,
        myCard:e.result.myinfo||null
      })
    })
  },
  tab(e){
    console.log(e.target.dataset.index)
    this.setData({
      tabIndex:e.target.dataset.index
    })
    // e.target.dataset.index == 1 ? this.getVip() : ''
  },
  // 充值
  choose_money(e){
    wx.showLoading({
      title: '请稍后',
    })
    var that = this
    var o = {
      card_id:that.data.card_id,
      store_id:that.data.store_id,
      config:that.data.InvestList[that.data.tabIndex].id
    }
    // 调充值接口
    t.request('/Recharge',o,function(e){
      console.log(e);
      if (e.code==200) {
				var params = e.result.params
				let order_sn = e.result.info.order_sn //订单编号
        wx.requestPayment({
          nonceStr: params.nonceStr,
          package: params.package,
          paySign: params.paySign,
          signType: 'MD5',
          timeStamp: params.timeStamp,
          'success'(e){
            wx.hideLoading({success: (res) => {},})
						//获取当前时间
						let now = new Date();
						let y = now.getFullYear(),m=now.getMonth() + 1,d=now.getDate(),h=now.getHours(),f=now.getMinutes(),s=now.getSeconds();
						that.setData({
							payTime:y+'-'+m+'-'+d+' '+h+":"+f+":"+s,
							orderNum:order_sn,
							seconds:3,
							showStatus:true
						})
						// 设置读秒器
						that.data.interval = setInterval(() => {
							setTimeout(that.intervalFun, 0);
						}, 1000)
          },
          'fail'(e){
            wx.hideLoading({
              success: (res) => {},
            })
            wx.showModal({
              title: '您取消了支付！',
              showCancel:false,
              complete:function(){
              }
            })
          },
        })
      }else{
        wx.showToast({
          title: e.msg,
          icon: 'none',
          duration: 2000
        })
        return false;
      }
    })
    this.setData({
      choosed_money:e.currentTarget.dataset.id
    })
  },
  // 买会员卡
  buy_vip(e){
    const that = this
    const o = {
      store_id:that.data.store_id,
      id:e.currentTarget.dataset.id
    }
    wx.showLoading({ title: '请稍后' })
    t.request('/recharge/vip',o,function(e){
      console.log(e);
      if (e.code!==200) return wx.showToast({ title: e.msg,icon:'none' })
      var params = e.result.params
      wx.requestPayment({
        nonceStr: params.nonceStr,
        package: params.package,
        paySign: params.paySign,
        signType: 'MD5',
        timeStamp: params.timeStamp,
        'success'(e){
          console.log(e);
          wx.hideLoading({
            success: (res) => {},
          })
          that.getVip()
        },
        'fail'(e){
          wx.hideLoading({
            success: (res) => {},
          })
          wx.showModal({
            title: '您取消了支付！',
            showCancel:false,
            complete:function(){
            }
          })
        },
      })
    })
    this.setData({
      choosed_card:e.currentTarget.dataset.id
    })
  },
  change_page(e){
    console.log(e);
    this.setData({
      change:e.currentTarget.dataset.index,
    })

  },
  change_page2(e){
    this.setData({
      change:e.currentTarget.dataset.index,
      page:1
    })
    this.getList_new();
  },
  gopre(){
    this.setData({
      page:this.data.page-1
    })
    this.getList();
  },
  gonext(){
    this.setData({
      page:this.data.page+1
    })
    this.getList();
	},
	// 洗车协议
  navto(e){
    wx.navigateTo({
      url: '/pages/article/article?id=334',
    })
	},
	// 计算回跳路径
	getLastUrl(){
		let url = ''
		let pages = getCurrentPages()
		if(pages.length<2){
			url = '/pages/index/index';
		}else{
			let option = pages[pages.length-2].options
			let lastUrl = pages[pages.length-2].route
				switch(lastUrl){
					case 'pages/personCenter/recharge/list':
							// 首页进来充值返回门店详情
							url= '/pages/store/store?store_id='+that.data.store_id+'&dis='+that.data.dis;
					break;
					case 'pages/code_start/code_start':
							//扫码入场页面 
							url= '/pages/code_start/code_start?site='+option.site+'&store='+option.store+'&ismini='+option.ismini
					break;
					case 'pages/store/store':
							//门店页面充值
							url= '/pages/store/store?store_id='+option.store_id+'&dis='+option.dis
					break;
					case 'pages/personCenter/mySc/mySc':
							//我的余额充值
							url= '/pages/personCenter/mySc/mySc'
					break;
					case 'pages/settle_accounts/settle_accounts':
						//扫码入场页面 
						url= '/pages/settle_accounts/settle_accounts?site='+option.site+'&store='+option.store
					break;
				}
		}
		console.log(url)
		this.setData({
			lastUrl:url
		})
	},
	// 支付成功返回上一页
	paySuccess(e){
		if(this.data.lastUrl == '/pages/index/index'){
			wx.switchTab({
				url: '/pages/index/index',
			})
		}else{
			wx.navigateTo({
				url: this.data.lastUrl
			})
		}
	},
	// 关闭支付成功弹窗
	exit(){
		this.setData({showStatus:false})
	},
	// 返回门店
	backStore(){
		wx.navigateTo({
			url: '/pages/store/store?store_id='+this.data.store_id+'&dis='+this.data.dis,
		})
	},
	// 测试支付成功弹出
	ceshi(){
			let that =this
			//获取当前时间
			let now = new Date();
			let y = now.getFullYear(),m=now.getMonth() + 1,d=now.getDate(),h=now.getHours(),f=now.getMinutes(),s=now.getSeconds();
			that.setData({
				payTime:y+'-'+m+'-'+d+' '+h+":"+f+":"+s,
				showStatus:true,
				seconds:3,
				orderNum:12346656
			})
			// 设置读秒器
			that.data.interval = setInterval(() => {
				setTimeout(that.intervalFun, 0);
			}, 1000)
	},
	// 读秒器
	intervalFun(){
		let that =this
		if(that.data.seconds<1){
			clearInterval(that.data.interval)
			that.paySuccess()
		}else{
			that.setData({
				seconds:that.data.seconds-1
			})
		}
	}
})